<template>
	<view class="canvasBox">
		<template v-if="isUse">
			<view class="box">
				<view class="line" ></view>
				<view class="angle"></view>
			</view>
			<view class="btn-box">
				<m-icon type="camera" wh="160" @click="tick"></m-icon>
			</view>
		</template>
		<template v-else>
			<slot name="error">
				<view class="error">
					<view class="on1">相机权限被拒绝，请尝试如下操作：</view>
					<view>· 刷新页面后重试；</view>
					<view>· 在系统中检测当前App或浏览器的相机权限是否被禁用；</view>
					<view>· 如果依然不能体验，建议在微信中打开链接；</view>
				</view>
			</slot>
		</template>
	</view>
</template>

<script>
	import { Upload2, } from '@/api/Ctrls.js'
	import {  Jump } from '@/utils/tools.js'
	export default {
		props: {
			continue: {
				type: Boolean,
				default: false // false 监听一次   true 持续监听
			},
			exact: {
				type: String,
				default: 'user' // environment 后摄像头  user 前摄像头
			},
			size: {
				type: String,
				default: 'whole' // whole 全屏  balf 半屏
			},
			definition: {
				type: Boolean,
				default: true // fasle 正常  true 高清
			}
		},
		data() {
			return {
				windowWidth: 0,
				windowHeight: 0,
				video: null,

				track: null,
				isUseTorch: false,
				trackStatus: false,

				isParse: false,
				isUse: true,
				stream: '',
				isLoading: false,
			}
		},
		mounted() {
			if (origin.indexOf('https') === -1) throw '请在 https 环境中使用摄像头组件。'

			this.windowWidth = document.documentElement.clientWidth || document.body.clientWidth
			this.windowHeight = document.documentElement.clientHeight || document.body.clientHeight
			this.windowHeight = this.size === 'whole' ? this.windowHeight : this.windowHeight / 2
			this.isParse = true

			this.$nextTick(() => {
				this.openScan()
			})
		},
		destroyed() {
			this.closeCamera()
		},
		methods: {
			openScan() {
				const width = this.transtion(this.windowHeight)
				const height = this.transtion(this.windowWidth)
				const videoParam = {
					audio: false,
					video: {
						facingMode: { exact: this.exact },
						width,
						height
					}
				}
				navigator.mediaDevices.getUserMedia(videoParam).then(stream => {
						this.video = document.createElement('video')
						this.video.width = this.windowWidth
						this.video.height = this.windowHeight
						// 设置当前宽高 满屏
						const canvasBox = document.querySelector('.canvasBox')
						canvasBox.append(this.video)


						this.video.srcObject = stream;
						this.stream = stream;
						this.video.setAttribute('playsinline', true)
						this.video.play()

						this.track = stream.getVideoTracks()[0]
						setTimeout(() => {
							this.isUseTorch = this.track.getCapabilities().torch || null
						}, 500)
					})
					.catch(err => {
						
						this.isUse = false
					})
			},
			closeCamera() {
				this.isParse = false
				if (this.video && this.video.srcObject) {
					this.video.srcObject.getTracks().forEach(track => {
						track.stop()
					})
				}
			},

			async tick() {
				console.log('拍照');
				if (!this.isParse) return
				if (this.video.readyState === this.video.HAVE_ENOUGH_DATA) {
					uni.showLoading()
					this.isLoading = true;

					let pixelRatio = window.devicePixelRatio || 1;
					let canvas = document.createElement('canvas');
					let ctx = canvas.getContext('2d');
					canvas.width = this.windowWidth * pixelRatio;
					canvas.height = this.windowHeight * pixelRatio;
					// 图片压缩
					ctx.drawImage(this.video, 0, 0, this.windowWidth, this.windowHeight)
					let base64 = canvas.toDataURL('image/png', 1);
					let flie = this.convertBase64UrlToFile({
						dataURL: base64,
						type: 'image/png',
						contentName: 'images.png'
					})
					const { success, data, msg } = await Upload2(flie)
					if (success) {
						uni.setStorageSync('faceImage', data);
						console.log(data)
						setTimeout(() => {
							Jump()
						}, 1000)
					} else {
						this.Toast(msg)
					}
					this.isLoading = true;
					uni.hideLoading()
				}
				// requestAnimationFrame(this.tick)
			},

			convertBase64UrlToFile(base64) {
				let urlData = base64.dataURL
				let type = base64.type
				let contentName = base64.contentName
				let bytes = null
				if (urlData.split(',').length > 1) { //是否带前缀
					bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
				} else {
					bytes = window.atob(urlData)
				}
				// 处理异常,将ascii码小于0的转换为大于0
				let ab = new ArrayBuffer(bytes.length)
				let ia = new Uint8Array(ab)
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i)
				}
				let result = new Blob([ab], {
					type: type,
				})
				let result1 = new File([result], contentName, {
					type: type
				})
				result1.path = window.URL.createObjectURL(result)
				return result1
			},

			transtion(number) {
				return this.definition ? number * 2.8 : number * 1.8
			},
			nutranstion(number) {
				return this.definition ? number / 2.8 : number / 1.8
			}
		}
	}
</script>

<style scoped>
	page {
		background-color: #333333;
	}

	.btn-box {
		position: fixed;
		bottom: 10%;
		left: 50%;
		transform: translateX(-50%);
		z-index: 9999;
	}

	.canvasBox {
		width: 100vw;
		height: 100vh;
		position: relative;

		background-image: linear-gradient(0deg,
				transparent 24%,
				rgba(32, 255, 77, 0.1) 25%,
				rgba(32, 255, 77, 0.1) 26%,
				transparent 27%,
				transparent 74%,
				rgba(32, 255, 77, 0.1) 75%,
				rgba(32, 255, 77, 0.1) 76%,
				transparent 77%,
				transparent),
			linear-gradient(90deg,
				transparent 24%,
				rgba(32, 255, 77, 0.1) 25%,
				rgba(32, 255, 77, 0.1) 26%,
				transparent 27%,
				transparent 74%,
				rgba(32, 255, 77, 0.1) 75%,
				rgba(32, 255, 77, 0.1) 76%,
				transparent 77%,
				transparent);
		background-size: 3rem 3rem;
		background-position: -1rem -1rem;
		z-index: 10;
		background-color: #1110;
	}

	.box {
		width: 100%;
		height: 100%;
		position: absolute;
		overflow: hidden;
		border: 0.1rem solid rgba(0, 255, 51, 0.2);
		z-index: 11;
	}

	.line {
		height: calc(100% - 2px);
		width: 100%;
		background: linear-gradient(180deg, rgba(0, 255, 51, 0) 43%, #00ff33 211%);
		border-bottom: 3px solid #00ff33;
		transform: translateY(-100%);
		animation: radar-beam 2s infinite alternate;
		animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
		animation-delay: 1.4s;
	}

	.line-paused {
		animation-play-state: paused;
	}

	.box:after,
	.box:before,
	.angle:after,
	.angle:before {
		content: '';
		display: block;
		position: absolute;
		width: 3vw;
		height: 3vw;
		z-index: 12;
		border: 0.2rem solid transparent;
	}

	.box:after,
	.box:before {
		top: 0;
		border-top-color: #00ff33;
	}

	.angle:after,
	.angle:before {
		bottom: 0;
		border-bottom-color: #00ff33;
	}

	.box:before,
	.angle:before {
		left: 0;
		border-left-color: #00ff33;
	}

	.box:after,
	.angle:after {
		right: 0;
		border-right-color: #00ff33;
	}

	@keyframes radar-beam {
		0% {
			transform: translateY(-100%);
		}

		100% {
			transform: translateY(0);
		}
	}

	.msg {
		text-align: center;
		padding: 20rpx 0;
	}

	.box2 {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		z-index: 20;
	}

	.track {
		position: absolute;
		bottom: -100px;
		left: 50%;
		transform: translateX(-50%);
		z-index: 20;
		color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.mask {
		position: absolute;
		z-index: 10;
		background-color: rgba(0, 0, 0, 0.55);
	}

	.mask1 {
		top: 0;
		left: 0;
		right: 0;
	}

	.mask2 {
		right: 0;
	}

	.mask3 {
		right: 0;
		left: 0;
		bottom: 0;
	}

	.mask4 {
		left: 0;
	}

	.error {
		color: #fff;
		padding: 40rpx;
		font-size: 24rpx;
		background-color: #333333;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 550rpx;
		border-radius: 20rpx;
	}

	.error .on1 {
		font-size: 30rpx;
	}
</style>